//const Sequelize = require("sequelize");
const Uuid = require('uuid');
let Models = require('../models');

module.exports = {
    getAds: function (request, reply) {
        var visitorId;
        if (!request.state.visitor) { 
            visitorId = Uuid.v1();
            reply.state('visitor', {id: visitorId});
        }
        else {
            visitorId = request.state.visitor.id;
        }

        return  Models.Slot.findOne({
            attributes: ['id', 'type', 'width', 'height', 'align_h', 'margin_h', 'align_v', 'margin_v', 
                'stay_time', 'scrolled', 'closable', 'schedule_mode', 'ad_count', 'rotate_interval', 'day_times'], 
            where: {
                id: request.query.id,
                enabled: 1
            }
        }).then(function (result) {
            let reponseMess = {};
            
            if (!result) {
                reponseMess = {
                    code: -1,
                    message: 'slot not found!',
                    data: ''
                }
                return reponseMess;
            } 
            var slot = result;
            
            //1、权重调度算法：单位权重已显示数，小者优先，这样权重小的也有相应的机会。
            //2、下面SQL-ORDER-BY中，"(...show_count + 1) / (p.fweight + 1)": 
            //（1）分子+1是避免不管分母为多少，结果都为0，+1才满足权重大的优先；
            //（2）分母+1是避免零除错误。
            return Models.sequelize.query(
                "SELECT a.*, p.id as put_id, p.click_countable \
                   FROM ads_putable p \
                  INNER JOIN ads_slot s\
                     ON p.slot_id = s.id\
                    AND p.slot_id = $slotId \
                    AND s.id = $slotId \
                    AND s.enabled = 1\
                  INNER JOIN ads_ad a \
                     ON p.ad_id = a.id \
                    AND a.enabled = 1 \
                   LEFT JOIN ads_visitor_stat v \
                     ON p.id = v.put_id \
                    AND v.visitor = $visitor \
                    AND v.visit_date = DATE(SYSDATE()) \
                  WHERE (p.day_times = 0 OR p.day_times > IFNULL(v.show_count, 0)) \
                  ORDER BY IF(p.weight < 10, 1, 0), \
                           CASE s.schedule_mode \
                                WHEN 11 THEN p.curr_show_count \
                                WHEN 12 THEN (p.curr_show_count + 1) / (p.weight + 1) \
                                WHEN 21 THEN p.show_count \
                                WHEN 22 THEN (p.show_count + 1) / (p.weight + 1) \
                                ELSE p.curr_show_count \
                            END  ASC \
                  LIMIT " + slot.ad_count, 
                {
                    type: Models.sequelize.QueryTypes.SELECT,
                    plain: false,
                    bind: {slotId: request.query.id, visitor: visitorId}
                }).then(function (result) {
                    if (result) {
                        reponseMess = {
                            code: 0,
                            message: 'success',
                            data: {slot: slot, ads: result}
                        }
                    } else {
                        reponseMess = {
                            code: -2,
                            message: 'no ad placed!',
                            data: ''
                        }                    
                    }
                    return reponseMess;
                });
        });
    },

    getSlot: function (request, reply) {
        return  Models.Slot.findOne({
            where: {
                id: request.query.id
            }
        }).then(function (result) {
            let reponseMess = {};
             if (result) {
                reponseMess = {
                    code: 100,
                    message: 'success',
                    data: result
                }
            } else {
                reponseMess = {
                    code: -100,
                    message: 'fail',
                    data: ''
                }
            }
            return reponseMess;
        });
    }
};